package com.limh.toast

import android.app.Application
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.Gravity
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat


object ToastUtils {
    private var myToast: Toast? = null
    private var application: Application? = null

    fun init(application: Application) {
        this.application = application
    }

    fun show(message: String) {
        checkToast()
        custom(message, null)
    }

    fun success(message: String) {
        checkToast()
        custom(message, ContextCompat.getDrawable(application!!, R.drawable.ic_toast_success))
    }

    fun error(message: String) {
        checkToast()
        custom(message, ContextCompat.getDrawable(application!!, R.drawable.ic_toast_warning))
    }

    private fun custom(message: String, drawable: Drawable?) {
        if (null == myToast) {
            myToast = Toast(application)
        }
        val textView = TextView(application)
        textView.gravity = Gravity.CENTER
        textView.text = message
        textView.setTextColor(Color.WHITE)
        textView.setPadding(20, 20, 20, 20)
        drawable?.let {
            textView.setPadding(40, 20, 40, 20)
            it.setBounds(0, 0, it.minimumWidth, it.minimumHeight)
            textView.setCompoundDrawables(null, it, null, null)
        }
        textView.background = ContextCompat.getDrawable(application!!, R.drawable.toast_frame_bg)
        myToast?.let {
            it.view = textView
            it.setGravity(Gravity.CENTER, 0, 0)
            it.duration = if (message.length > 10) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
            it.show()
        }
    }

    private fun checkToast() {
        if (null == application) {
            throw IllegalStateException("ToastUtils has not been initialized")
        }
    }
}
